// pages/delivery-order/index.js
import config from '../../etc/config'
var util = require('../../utils/util.js');

const {
  $Toast
} = require('../../components/dist/base/index');
Page({


  /**
   * 页面的初始数据
   */
  data: {
    key: '',
    showOrderList: [{
      orderAmount: '',
    }],
    orderId: '',
    buyerRemake: '',
    current: '1',
    subCurrent: '1',
    hiddenparts: true, // 隐藏或者显示弹框
    hiddenconfirmation: true,
    hiddentime: true,
    hiddennoPay: true,
    hiddenreform: true,
    money: '',
    endReason: '',
    merList: [{
      id: '',
    }],
    sellerRemake: '',
    scheduledTime: '',
    orderAmount: '',
    startProduceDate: '2019-01-01',
    endProduceDate: '2030-01-01',
    selectedProduceDate: '',
    currentPage: 1,
    time: '12:01',
    index: '',
    id: '',
    canDrawMoney: '',
    showModalStatus: false,
    obligationList: [],
    seversList: []
  },

  onLoad: function(options) {
    wx.hideShareMenu()
  },

  //获取配送单列表
  getshowOrder(key) {
    let params = {
      userId: wx.getStorageSync('userId'),
      orderStatus: key,
      currentPage: this.data.currentPage
    }
    let token = wx.getStorageSync('token')
    config._post('/deliverymanOrder/showOrder', token, params).then(res => {
      console.log(res)
      if (key == 1) {
        for (let i = 0; i < res.data.list.length; i++) {
          if (res.data.list[i].payStatus == 3) {
            this.data.obligationList.push(res.data.list[i])
          } else {
            this.data.seversList.push(res.data.list[i])
          }
        }
        if (this.data.subCurrent == 1) {
          this.setData({
            showOrderList: this.data.seversList,
          })
        } else {
          this.setData({
            showOrderList: this.data.obligationList
          })
        }
      } else {
        let list = res.data.list
        if (list.length > 0) {
          for (let i = 0; i < list.length; i++) {
            this.data.showOrderList.push(list[i])
          }
          this.setData({
            showOrderList: this.data.showOrderList,
          })
        }
      }
      wx.stopPullDownRefresh()
    })
  },

  //切换订单状态 -----未完成、已完成
  handleChange(e) {
    this.setData({
      current: e.detail.key,
      showOrderList: []
    })
    this.data.currentPage = 1
    this.data.obligationList = []
    this.data.seversList = []
    this.getshowOrder(e.detail.key)
  },

  //切换订单状态 -----服务中、待付款
  suHandleChange(e) {
    this.setData({
      subCurrent: e.target.dataset.key
    })
    if (this.data.subCurrent == 1) {
      this.setData({
        showOrderList: this.data.seversList
      })
    } else {
      this.setData({
        showOrderList: this.data.obligationList
      })
    }
  },

  // 查看订单详情
  enterContentDetail(e) {
    wx.navigateTo({
      url: '../order-detail/index?orderId=' + e.currentTarget.dataset.orderid,
    })
  },

  // 快捷拨号
  call(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.mobile //仅为示例，并非真实的电话号码
    })
  },

  // 删除订单
  delOrder(e) {
    var that = this;
    let params = {
      orderId: e.currentTarget.dataset.orderid,
    }
    let token = wx.getStorageSync('token')
    wx.showModal({
      title: '提示',
      content: '确认删除订单吗？',
      success(res) {
        if (res.confirm == true) {
          config._post('/deliverymanOrder/delDeliverOrder', token, params).then(res => {
            if (res.code == 0) {
              $Toast({
                content: '订单已删除'
              })
              that.data.showOrderList = [];
              that.data.currentPage = 1
              that.getshowOrder(2)
            }
          })
        } else if (res.cancel == false) {}
      }
    })
  },

  // 打开需要配件
  parts(e) {
    this.setData({
      hiddenparts: !this.data.hiddenparts,
      orderId: e.currentTarget.dataset.orderid,
    })
  },
  // 输入配件
  sellerRemakeInput: function (e) {
    this.setData({
      sellerRemake: e.detail.value
    })
  },
  // 配件确认
  confirmParts(e) {
    let params = {
      orderId: this.data.orderId,
      secondRepairRemake: this.data.sellerRemake,
      secondRepairTimeStr: this.data.selectedProduceDate
    }
    let token = wx.getStorageSync('token')
    config._post('/deliverymanOrder/needParts', token, params).then(res => {
      if (res.code == 0) {
        this.setData({
          hiddenparts: true,
          sellerRemake: ''
        })
        this.data.obligationList = [];
        this.data.seversList = [];
        this.data.currentPage = 1
        this.getshowOrder(1)
      }
    })
  },

  // 获取系统当前时间
  dateChange: function (e) {
    this.setData({
      selectedProduceDate: e.detail.value
    })
  },

  // 预计到达时间
  time(e) {
    this.setData({
      hiddentime: !this.data.hiddentime,
      orderId: e.currentTarget.dataset.orderid,
    })
    var DATE = util.formatDate(new Date());
    this.setData({
      selectedProduceDate: DATE,
    });
    var TIME = util.formatTime(new Date());
    this.setData({
      time: TIME,
    });
  },
  // 改变时间
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },
  // 确认预计到达时间
  confirmtime() {
    let params = {
      orderId: this.data.orderId,
      scheduledTimeStr: this.data.selectedProduceDate + ' ' + this.data.time + ':00'
    }
    let token = wx.getStorageSync('token')
    config._post('/deliverymanOrder/orderScheduledTime', token, params).then(res => {
      if (res.code == 0) {
        this.setData({
          hiddentime: true
        })
        this.data.obligationList = [];
        this.data.seversList = [];
        this.data.currentPage = 1
        this.getshowOrder(1)
      }
    })
  },

  // 打开改派订单
  reform(e) {
    this.setData({
      hiddenreform: !this.data.hiddenreform,
      orderId: e.currentTarget.dataset.orderid,
    })
  },
  powerDrawer: function(e) {
    var currentStatu = e.currentTarget.dataset.status;
    this.util()
  },
  util: function() {
    /* 动画部分 */
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200, //动画时长
      timingFunction: "linear", //线性
      delay: 0 //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是240px)，停
    animation.translateY(this.data.height * 0.6).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function() {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })
      //关闭抽屉
      this.setData({
        showModalStatus: false
      });
    }.bind(this), 500)
  },
  // 获取商铺列表
  shops(e) {
    let params = {
      orderId: e.currentTarget.dataset.orderid,
      userId: wx.getStorageSync('userId')
    }
    let token = wx.getStorageSync('token')
    config._post('/shop/getShopByDeliverUserId', token, params).then(res => {
      if (res.code == 0) {
        this.setData({
          merList: res.data,
          showModalStatus: true
        })
      }
    })
  },
  //改派订单
  confirreform(e) {
    let params = {
      shopId: e.currentTarget.dataset.id,
      orderId: this.data.orderId
    }
    let token = wx.getStorageSync('token')
    config._post('/deliverymanOrder/deliverChangeOrder', token, params).then(res => {
      if (res.code == 0) {
        this.setData({
          showModalStatus: false
        })
        this.data.obligationList = [];
        this.data.seversList = [];
        this.data.currentPage = 1
        this.getshowOrder(1)
      }
    })
  },

  // 打开输入金额（确认送达）
  confirmation(e) {
    this.setData({
      hiddenconfirmation: !this.data.hiddenconfirmation,
      orderId: e.currentTarget.dataset.orderid,
      buyerRemake: e.currentTarget.dataset.buyerremake,
    })
  },
  // 输入金额
  handleInput(e) {
    var money;
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) { //正则验证，提现金额小数点后不能大于两位数字
      money = e.detail.value;
    } else {
      money = e.detail.value.substring(0, e.detail.value.length - 1);
    }
    this.setData({
      money: money,
    })
  },
  endReasonInput(e){
    this.setData({
      endReason:e.detail.value
    })
  },
  // 确认金额
  confirmMatio() {
    if (this.data.money === 0) {
      $Toast({
        content: '输入金额不能为0'
      })
      return false
    }
    let params = {
      orderId: this.data.orderId,
      orderAmount: this.data.money,
      buyerRemake: this.data.buyerRemake
    }
    let token = wx.getStorageSync('token')
    config._post('/deliverymanOrder/collectionOrder', token, params).then(res => {
      if (res.code == 0) {
        wx.navigateTo({
          url: '../qrcode/index?orderId=' + this.data.orderId + '&buyerRemake=' + this.data.buyerRemake
        })
        this.data.obligationList = [];
        this.data.seversList = [];
        this.data.currentPage = 1
        this.getshowOrder(1)
        this.setData({
          hiddenconfirmation: true,
          money: ''
        })
      }
    })
  },

  // 无需付款
  noPay(e) {
    this.setData({
      hiddennoPay: !this.data.hiddennoPay,
      orderId: e.currentTarget.dataset.orderid,
    })
  },
  // 确认无需付款
  confirmnoPay() {
    let params = {
      orderId: this.data.orderId,
      endReason: this.data.endReason
    }
    let token = wx.getStorageSync('token')
    config._post('/deliverymanOrder/deliverEndOrder', token, params).then(res => {
      if (res.code == 0) {
        this.setData({
          hiddennoPay: true
        })
        this.data.obligationList = [];
        this.data.seversList = [];
        this.data.currentPage = 1
        this.getshowOrder(1)
      }
    })
  },

  // 确认送还衣服
  deliverCollectionOrder(e) {
    this.setData({
      orderId: e.currentTarget.dataset.orderid,
    })
    let params = {
      orderId: this.data.orderId,
    }
    let token = wx.getStorageSync('token')
    config._post('/deliverymanOrder/deliverCollectionOrder', token, params).then(res => {
      if (res.code == 0) {
        $Toast({
          content: '送还成功'
        })
        this.data.obligationList = [];
        this.data.seversList = [];
        this.data.currentPage = 1
        this.getshowOrder(1)
      }
    })
  },

  // 关闭弹窗
  cancel: function() {
    this.setData({
      hiddenparts: true,
      hiddenconfirmation: true,
      hiddentime: true,
      hiddennoPay: true,
      hiddenreform: true,
      money: '',
      sellerRemake: '',
      selectedProduceDate: this.data.selectedProduceDate
    })
  },

  // scheduledTimeInput: function(e) {
  //   this.setData({
  //     scheduledTime: e.detail.value
  //   })
  // },


  // // 二维码
  // qrcode(e) {
  //   this.setData({
  //     orderId: e.currentTarget.dataset.orderid,
  //     buyerRemake: e.currentTarget.dataset.buyerremake,
  //   })
  //   let params = {
  //     orderId: this.data.orderId,
  //     subject: this.data.buyerRemake,
  //   }
  //   wx.navigateTo({
  //     url: '../qrcode/index?orderId=' + this.data.orderId + '&buyerRemake=' + this.data.buyerRemake
  //   })
  // },
  

  // orderamount: function(e) {
  //   this.setData({
  //     orderAmount: e.detail.value
  //   })
  // },

  // // 改派订单
  // bindPickerChange(e) {
  //   this.setData({
  //     index: e.detail.value
  //   })
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.data.showOrderList = [];
    this.data.obligationList = [];
    this.data.seversList = [];
    this.data.currentPage = 1,
    this.getshowOrder(this.data.current)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      currentPage: 1,
      showOrderList: [],
      obligationList: [],
      seversList: []
    })
    this.getshowOrder(this.data.current)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.data.currentPage += 1
    this.getshowOrder(this.data.current)
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})